package es.buffygilmore.gastosapp;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import es.buffygilmore.gastosapp.vo.Evento;

public class EventoDetalle extends Activity {

	private EditText mTitleText;
	private Long mRowId;
	private GastosAppDbAdapter mDbHelper;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.mDbHelper = new GastosAppDbAdapter(this);

		this.mDbHelper.open();

		this.setContentView(R.layout.edicion_evento);
		this.setTitle(R.string.edit_note);

		this.mTitleText = (EditText) this.findViewById(R.id.titulo_evento);

		final Button confirmButton = (Button) this.findViewById(R.id.guardar_evento);

		this.mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState
				.getSerializable(GastosAppDbAdapter.KEY_EVENTO_ROWID);
		if (this.mRowId == null) {
			final Bundle extras = this.getIntent().getExtras();
			this.mRowId = extras != null ? extras.getLong(GastosAppDbAdapter.KEY_EVENTO_ROWID)
					: null;
		}

		this.populateFields();

		confirmButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(final View view) {
				EventoDetalle.this.setResult(RESULT_OK);
				EventoDetalle.this.finish();
			}

		});
	}

	private void populateFields() {
		if (this.mRowId != null) {
			final Cursor evento = this.mDbHelper.obtenerEvento(this.mRowId);
			this.startManagingCursor(evento);
			this.mTitleText.setText(evento.getString(evento
					.getColumnIndexOrThrow(GastosAppDbAdapter.KEY_EVENTO_TITULO)));
		}
	}

	@Override
	protected void onSaveInstanceState(final Bundle outState) {
		super.onSaveInstanceState(outState);
		this.saveState();
		outState.putSerializable(GastosAppDbAdapter.KEY_EVENTO_ROWID, this.mRowId);
	}

	@Override
	protected void onPause() {
		super.onPause();
		this.saveState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.populateFields();
	}

	private void saveState() {
		final Evento evento = new Evento();
		evento.setTitulo(this.mTitleText.getText().toString());

		if (this.mRowId == null) {
			final long id = this.mDbHelper.crearEvento(evento);
			if (id > 0) {
				this.mRowId = id;
			}
		} else {
			evento.setId(this.mRowId);
			this.mDbHelper.modificarEvento(evento);
		}
	}
}
